package com.changgou.system.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetAddress;
import java.net.InetSocketAddress;

/***
 * ip全局过滤器
 */

@Component
public class IpFilter implements GlobalFilter, Ordered {

    /***
     * 具体业务逻辑
     * @param exchange
     * @param chain
     * @return
     */

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //获取客户端的访问ip
        System.out.println("已经进入到IpFilter");

        ServerHttpRequest request = exchange.getRequest();
        //ServerHttpResponse response = exchange.getResponse();
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        String hostName = remoteAddress.getHostName();
        System.out.println("客户的远程地址是:" + hostName);

        //业务逻辑
        //从数据库 拿出黑客的ip List<String> blackIps
        //if (hostName == blackIps)
        //response
        //response.setStatusCode(HttpStatus.UNAUTHORIZED);
        //return response.setComplete();

        //放行
        return chain.filter(exchange);
    }

    /***
     * 过滤器的执行顺序 越小越先执行
     * @return
     */
    @Override
    public int getOrder() {
        return 1;
    }
}
